﻿using System;
using System.Collections.Generic;

using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Transactions;
using Orders.Utils;
using System.Data;
using System.Data.SqlClient;

namespace OrderServer
{
  public class AddProducts : IAddProducts
  {

    #region IAddProducts Members

    public void AddProduct(string Name, float Price, int Amount)
    {
      try
      {
        using (TransactionScope scope = new TransactionScope())
        {
          using (SqlConnection conn = new SqlConnection(DatabaseConnection.ConnectionString))
          {
            conn.Open();
            string prodID = Guid.NewGuid().ToString();
            //update Products Table
            using (SqlCommand cmd = new SqlCommand("insert into products(name,productid,price,added) values(@name,@productid,@price,@added)", conn))
            {
              cmd.Parameters.Add(new SqlParameter("@productid", prodID));
              cmd.Parameters.Add(new SqlParameter("@name", Name));
              cmd.Parameters.Add(new SqlParameter("@price", Price));
              cmd.Parameters.Add(new SqlParameter("@added", DateTime.Now.ToUniversalTime()));
              cmd.ExecuteNonQuery();
            }
            //update Stock Table
            using (SqlCommand cmd = new SqlCommand("insert into stock(productid,stockamount) values(@productid,@amount)", conn))
            {
              cmd.Parameters.Add(new SqlParameter("@productid", prodID));
              cmd.Parameters.Add(new SqlParameter("@amount", Amount));
              cmd.ExecuteNonQuery();
            }

          }
          scope.Complete();
        }
      }
      catch(Exception ex)
      {
        EventLogHandler.LogError("Could not add product: " + Name + ". " + ex.Message);
        throw;


      }
    }

    #endregion
  }
}
